import Vue from "vue";
import Router from "vue-router";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import routes from "./routeConfig";
import store from "../store";
import { getToken } from "xqjr-module-auth"; // get token from cookie
import { cancelToken } from "@/utils/request";

Vue.use(Router);
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const createRouter = () =>
  new Router({
    scrollBehavior: () => ({
      y: 0
    }),
    routes: routes
  });

const router = createRouter();

// no redirect whitelist
const whiteList = [
  "/",
  "/index",
  "/download",
  "/auth/login",
  "/auth/forget",
  "/home/index",
  "/console/initSite",
  "/renlizhiku",
  "/gys_reg"
];

// 返回上一个页面，滚动条回到顶部
router.beforeEach(async (to, from, next) => {
  cancelToken.forEach((item) => {
    item.routeChangeCancel && item.cancel();
  });

  NProgress.start();

  if (from.path === "/auth/login") {
    const hrefs = location.href.split("#");
    if (hrefs[0].indexOf("?") > 0) {
      const newHref = hrefs[0].substring(0, hrefs[0].indexOf("?")) + "#" + (!!hrefs[1] ? hrefs[1] : "");
      history.pushState({}, 0, newHref);
    }
  }

  const token = getToken();
  if (!!token) {
    if (to.path === "/auth/login") {
      next({ path: "/" });
    } else if (to.path === "/renlizhiku") {
      next();
    } else if (to.path === "/empty") {
      // const permissionStringList = store.getters.permissions.permissionStringList;
      // let flag = false;
      // for (let i = 1; i < permissionStringList.length; i++) {
      //   if (permissionStringList[i].split(":")[0] === "hr") {
      //     flag = true;
      //     break;
      //   }
      // }
      // if (flag) {
      //   next({ path: "/admin" });
      // }
      next();
      // } else if (to.path.includes("auth")) {
      //   next();
    } else {
      // if (store.state.auth.loaded && !(store.getters.permissions_menu && store.getters.permissions_menu.length > 0)) {
      //   next({ path: "/empty" });
      // } else {
      next();
      // const userInfo = localStorage.getItem("userinfo");
      // if (!!userInfo) {
      //   next();
      // } else {
      //   await store.dispatch("auth/loadUserInfo");
      //   next();
      // }
      // }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/auth/login?redirect=${to.path}`);
    }
  }
});

router.afterEach((to, from) => {
  toFromClean(
    to,
    from,
    [{ fromPath: "/shebao/shebaoManage/shebaoDetail", toPath: "/shebao/myClientele/imports/batchShebaoImports" }],
    "cbgl_condition"
  ); // 1、社保-参保管理-批量修改
  toFromClean(to, from, [{ fromPath: "/paySalary/applyFor", toPath: "/paySalary/info" }], "fxsq_condition"); // 薪资代发-发薪申请-进入详情
  toFromClean(
    to,
    from,
    [
      { fromPath: "/paySalary/examine", toPath: "/paySalary/examineDetail" },
      { fromPath: "/paySalary/examine", toPath: "/newApproval" }
    ],
    "fxsh_condition"
  ); // 1、薪资代发-发薪审批-进入详情 2、薪资代发-发薪审批-进入审批
  toFromClean(to, from, [{ fromPath: "/paySalary/pay", toPath: "/paySalary/examineDetail" }], "xzff_condition"); // 1、薪资代发-薪资发放-进入详情
  toFromClean(to, from, [{ fromPath: "/wages/file", toPath: "/file/outsourcingDetail" }], "xzda_condition"); // 1、薪资-薪资档案-待定薪&工价-进入详情
  toFromClean(
    to,
    from,
    [
      { fromPath: "/staff/employee", toPath: "/staff/detail" },
      { fromPath: "/staff/employee", toPath: "/staff/employee/todayAdd" },
      { fromPath: "/staff/employee", toPath: "/staff/upload" },
      { fromPath: "/staff/employee", toPath: "/staff/batchEdit" },
      { fromPath: "/staff/employee", toPath: "/staff/uploadFile" },
      { fromPath: "/staff/detail", toPath: "/staff/detail" }
    ],
    "yghmc_condition"
  ); // 1、花名册-进入详情 2、花名册-今日新增 3、花名册-批量导入新员工 4、花名册-批量修改员工信息 5、花名册-批量导入合同 6、个人档案tabs切换
  NProgress.done();
  window.scrollTo(0, 0);
});

function toFromClean(to, from, pathList, cacheKey) {
  let isRemove = true;
  for (let i = 0; i < pathList.length; i++) {
    if (
      (to.fullPath.includes(pathList[i].fromPath) && from.fullPath.includes(pathList[i].toPath)) ||
      (to.fullPath.includes(pathList[i].toPath) && from.fullPath.includes(pathList[i].fromPath))
    ) {
      isRemove = false;
      break;
    }
  }
  if (isRemove) {
    localStorage.removeItem(`${cacheKey}_condition`);
    localStorage.removeItem(`${cacheKey}_pageSize`);
    localStorage.removeItem(`${cacheKey}_page`);
  }
}

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}

export default router;
